package org.codehaus.activemq.axis;

import java.util.HashMap;
import javax.jms.ConnectionFactory;
import javax.jms.QueueConnectionFactory;
import javax.jms.TopicConnectionFactory;
import org.apache.axis.components.jms.BeanVendorAdapter;
import org.apache.axis.transport.jms.JMSURLHelper;
import org.codehaus.activemq.ActiveMQConnectionFactory;

public class ActiveMQVendorAdapter extends BeanVendorAdapter
{
  protected static final String QCF_CLASS = ActiveMQConnectionFactory.class.getName();
  protected static final String TCF_CLASS = QCF_CLASS;
  public static final String BROKER_URL = "brokerURL";
  public static final String DEFAULT_USERNAME = "defaultUser";
  public static final String DEFAULT_PASSWORD = "defaultPassword";
  public static final String EMBEDDED_BROKER = "embeddedBroker";

  public QueueConnectionFactory getQueueConnectionFactory(HashMap properties)
    throws Exception
  {
    properties = (HashMap)properties.clone();
    properties.put("transport.jms.ConnectionFactoryClass", QCF_CLASS);
    return super.getQueueConnectionFactory(properties);
  }

  public TopicConnectionFactory getTopicConnectionFactory(HashMap properties) throws Exception
  {
    properties = (HashMap)properties.clone();
    properties.put("transport.jms.ConnectionFactoryClass", TCF_CLASS);
    return super.getTopicConnectionFactory(properties);
  }

  public void addVendorConnectionFactoryProperties(JMSURLHelper jmsUrl, HashMap properties)
  {
    if (jmsUrl.getPropertyValue("brokerURL") != null) {
      properties.put("brokerURL", jmsUrl.getPropertyValue("brokerURL"));
    }

    if (jmsUrl.getPropertyValue("defaultUser") != null) {
      properties.put("defaultUser", jmsUrl.getPropertyValue("defaultUser"));
    }
    if (jmsUrl.getPropertyValue("defaultPassword") != null) {
      properties.put("defaultPassword", jmsUrl.getPropertyValue("defaultPassword"));
    }
    if (jmsUrl.getPropertyValue("embeddedBroker") != null)
      properties.put("embeddedBroker", jmsUrl.getPropertyValue("embeddedBroker"));
  }

  public boolean isMatchingConnectionFactory(ConnectionFactory connectionFactory, JMSURLHelper jmsURL, HashMap properties)
  {
    String brokerURL = null;
    boolean embeddedBroker = false;

    if ((connectionFactory instanceof ActiveMQConnectionFactory)) {
      ActiveMQConnectionFactory amqConnectionFactory = (ActiveMQConnectionFactory)connectionFactory;

      brokerURL = amqConnectionFactory.getBrokerURL();
      embeddedBroker = amqConnectionFactory.isUseEmbeddedBroker();
    }

    String propertyBrokerURL = (String)properties.get("brokerURL");
    if (!brokerURL.equals(propertyBrokerURL)) {
      return false;
    }

    String tmpEmbeddedBroker = (String)properties.get("embeddedBroker");
    boolean propertyEmbeddedBroker = false;
    if (tmpEmbeddedBroker != null) {
      propertyEmbeddedBroker = Boolean.valueOf(tmpEmbeddedBroker).booleanValue();
    }

    return embeddedBroker == propertyEmbeddedBroker;
  }
}